// 在http.js中引入axios
import Vue from 'vue'
import axios from 'axios'; // 引入axios
import QS from 'qs'; // 引入qs模块，用来序列化post类型的数据，后面会提到
import {debounce} from '@/util'
import NProgress from "../progress";
import store from '@/store'
const instance = axios.create({
  baseURL:url,
  withCredentials: true
});
instance.defaults.timeout = 10000;
instance.defaults.headers['Content-Type'] = 'application/json;charset=UTF-8';
let count = 0
const isConnectJava = store.state.setting.isConnectJava
instance.interceptors.request.use(function (config) {
  store.commit('SET_IS_OUT_OF_INTERNET',!navigator.onLine)
  if(!navigator.onLine)return
  const params = config.hasOwnProperty('params') ? config.params : config.data
  // params.interval || count++ || NProgress.start()
  delete params.interval
  return config;
}, function (error) {
  // 对请求错误做些什么
  return Promise.reject(error);
});
// 响应拦截器
instance.interceptors.response.use(
  response => {
    const cookie = response.headers['Set-Cookie'] || response.headers['set-cookie'];
    console.log(cookie);
    const {$message} = Vue.prototype
    count > 0 && --count || NProgress.done()
    // 如果返回的状态码为200，说明接口请求成功，可以正常拿到数据
    // 否则的话抛出错误

    if (response.status === 200) {
      const data = response.data
      if(!isConnectJava){
        return Promise.resolve(data)
      }
      if (typeof data === 'object') {
        if (data.hasOwnProperty('code')) {
          const code = data.code
          const msg = data.msg
          if (code === '200') {
            let res = data.hasOwnProperty('total') ? data : data
            return Promise.resolve(res);
          } else {
            if(msg){
              $message.error(msg);
            }
            else {
              $message.error('连接后台失败');
            }
            return Promise.reject(data);
          }
        } else {
          return Promise.resolve(data);
        }
      } else {
        return Promise.resolve(data);
      }
    } else {
      return Promise.reject({code: response.status});
    }
  },
  error => {
    const {$message} = Vue.prototype
    if (error.response.status) {
      switch (error.response.status) {
        // 401: 未登录
        // 未登录则跳转登录页面，并携带当前页面的路径
        // 在登录成功后返回当前页面，这一步需要在登录页操作。
        // case 401:
        //   router.replace({
        //     path: '/login',
        //     query: {
        //       redirect: router.currentRoute.fullPath
        //     }
        //   });
        //   break;

        // case 403:
        //   Message.warning('登录过期，请重新登录');
        //   // 清除token
        //   localStorage.removeItem('token');
        //   store.commit('loginSuccess', null);
        //   // 跳转登录页面，并将要浏览的页面fullPath传过去，登录成功后跳转需要访问的页面
        //   setTimeout(() => {
        //     router.replace({
        //       path: '/login',
        //       query: {
        //         redirect: router.currentRoute.fullPath
        //       }
        //     });
        //   }, 1000);
        //   break;

        // 404请求不存在
        case 404:
          $message.warning('网络请求不存在');
          break;
        // 其他错误，直接抛出错误提示
        default:
          $message.error(error.response.data.message);
      }
      return Promise.reject(error.response);
    }
  }
)

/**
 * get方法，对应get请求
 * @param {String} url [请求的url地址]
 * @param {Object} params [请求时携带的参数]
 */
function get(url, params = {}, interval = false) {
  params.interval = interval
  return new Promise((resolve, reject) => {
    instance.get(url, {
      params: params
    }).then(res => {
      resolve(res);
    }).catch(err => {
      reject(err)
    })
  });
}
function getWithPage(url, params = {}, interval = false) {
  const {currentPage, pageSize} = params
  delete params.currentPage
  delete params.pageSize
  url = `${url}?pageSize=${pageSize}&pageNum=${currentPage}`
  return get(url, params, interval)
}
/**
 * post方法，对应post请求
 * @param {String} url [请求的url地址]
 * @param {Object} params [请求时携带的参数]
 */
function post(url, params = {}, interval = false) {
  params.interval = interval
  return new Promise((resolve, reject) => {
    instance.post(url, params)
      .then(res => {
        resolve(res);
      }).catch(err => {
      reject(err)
    })
  });
}
function handlePage(url, data) {
  // if(!data||typeof )
  return url

}
const request = function (options = {}, interval = false) {
  options.hasOwnProperty('method') || (options.method = 'get')
  const key = options.method === 'get' ? 'params' : 'data'
  options[key] ? (options[key].interval = interval) : (options[key] = {})['interval'] = interval
  return new Promise((resolve, reject) => {
    instance(options).then(res => {
      resolve(res)
    }).catch(err => {
      reject(err)
    })
  })
}



request.getWithPage = getWithPage
request.get = get
request.post = post

export default {
  install: function (Vue) {
    Vue.prototype.$http = request
  }
}
